<template>
    <!-- 核价统计 -->
    <div class="home">
        <div class="home_top">
            <el-form :model="queryParmas" :inline="true" label-width="120px">
                <el-form-item>
                    <el-radio-group v-model="queryParmas.status" is-button @change="statusChange">
                        <el-radio-button label="今日视图" />
                        <el-radio-button label="本周视图" />
                        <el-radio-button label="本月视图" />
                        <el-radio-button label="本年视图" />
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-date-picker size="large" v-model="queryParmas.date" type="daterange" range-separator="~"
                        start-placeholder="开始时间" end-placeholder="结束时间" :clearable="false" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item>
                    <el-button class="home_top_button" type="primary" @click="onSubmitOne">检索</el-button>
                </el-form-item>
            </el-form>
        </div>
        <Simple v-loading="viewCountLoading" :data="viewCountData" />
        <div class="chart">
            <div class="chart_form">
                <el-form :model="queryParmas" :inline="true" label-width="120px">
                    <el-form-item>
                        <div class="form_tabs">
                            <div v-for="item in chartTabsList" :key="item.id"
                                :class="{ form_tabs_item: true, form_tabs_item_active: item.id === chartTabsId }"
                                @click="chartTabsClick(item.id)">
                                {{ item.name }}</div>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <el-date-picker size="large" v-model="queryParmas.dateOne" type="daterange" range-separator="~"
                            start-placeholder="开始时间" end-placeholder="结束时间" :clearable="false"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item>
                        <el-button class="chart_form_button" type="primary" @click="onSubmitTwo">检索</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="chart_box">
                <div class="chart_box_bar">
                    <div class="bar_chart" ref="chartBarDom"></div>
                    <div class="bar_text">各部门资质审批情况统计图</div>
                </div>
                <div class="chart_box_pie" ref="chartPieDom" v-loading="pieLoading">
                </div>
            </div>
        </div>
        <div class="tableOne">
            <div class="tableOne_title">
                各部门审批数据汇总
                <!-- <span class="red">当前仅可导出9月6日以后得数据</span> -->
                <span class="span"></span>
            </div>
            <TableOne v-if="chartTabsId === 1" :tableData="tableDataOne" v-loading="tableOneLoading" />
            <TableTwo v-if="chartTabsId === 2" :tableData="tableDataTwo" v-loading="tableTwoLoading" />
        </div>
        <div class="tableTwo">
            <div class="tableTwo_title">
                各部门审批数据详细信息
                <span class="span"></span>
                <div class="export_button" @click="handleExport">导出</div>
            </div>
            <div class="tableTwo_tabs">
                <el-tabs v-model="queryParmas.recruiterDeptId" class="demo-tabs" @tab-change="handleClick">
                    <el-tab-pane v-for="item in tabsData" :key="item.deptId" :label="item.deptName"
                        :name="item.deptId" />
                </el-tabs>
            </div>
            <TableThree v-loading="tableThreeLoading" :tableData="tableDataThree"
                :isRow="tabsId === queryParmas.recruiterDeptId" :chartTabsId="chartTabsId">
                <pagination v-show="tableThreeTotal > 0" :total="tableThreeTotal" v-model:page="queryParmas.pageNum"
                    v-model:limit="queryParmas.pageSize" @pagination="GetDeptDataList" />
            </TableThree>
        </div>
    </div>
</template>
<script setup>
const { proxy } = getCurrentInstance();
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts';
import { dayjs } from 'element-plus'
import elementResizeDetectorMaker from 'element-resize-detector'
import { bigNumberTransform } from '@/utils/index'
import { debounce } from 'lodash'
import { getDeptViewCont, getViewCount, getDeptData, getDeptDataSecond, getDeptDataList, getSystemList, getDeptDataListSecond, getDataDeptProportion } from '@/api/group/pricingStatistics/index'
import Simple from './components/simple/index.vue'
import TableOne from './components/tableOne/index.vue'
import TableTwo from './components/tableTwo/index.vue'
import TableThree from './components/tableThree/index.vue'
const erd = elementResizeDetectorMaker();
const router = useRouter();
const chartPieDom = ref(null);
const chartBarDom = ref(null)
let chartInstancePie = null;
let chartInstanceBar = null

const chartTabsList = ref([
    { name: '核价初审', id: 1 },
    { name: '核价复审', id: 2 }
])
const chartTabsId = ref(1)
const queryParmas = ref({
    status: '今日视图',
    date: [],
    dateOne: [],
    pageNum: 1,
    pageSize: 10,
    recruiterDeptId: ''
})
// 头部统计
const viewCountData = ref(null)
const viewCountLoading = ref(false)
// 柱状图统计
const deptViewContData = ref(null)
const deptViewContLoading = ref(false)
// 饼图loading
const pieDataOne = ref([])
const pieDataTwo = ref([])
const pieName = ref([])
const pieLoading = ref(false)
// 初审汇总统计
const tableDataOne = ref([])
const tableOneLoading = ref(false)
// 复审汇总统计
const tableDataTwo = ref([])
const tableTwoLoading = ref(false)
// 各部门审批数据详细信息
const tableDataThree = ref([])
const tableThreeLoading = ref(false)
const tableThreeTotal = ref(0)
// 各部门审批数据详细信息-tabs
const tabsData = ref([])
const tabsId = ref('')

// 顶部统计
const getListOne = async () => {
    const params = {
        startDate: queryParmas.value.date && queryParmas.value.date[0] || '',
        endDate: queryParmas.value.date && queryParmas.value.date[1] || ''
    }
    GetViewCount(params)
}
// 柱状图统计
const getListTwo = async () => {
    const params = {
        startDate: queryParmas.value.dateOne && queryParmas.value.dateOne[0] || '',
        endDate: queryParmas.value.dateOne && queryParmas.value.dateOne[1] || ''
    }
    GetDeptViewCont(params)
    GetDataDeptProportion(params)
    if (chartTabsId.value === 1) {
        GetDeptData(params)
    } else {
        GetDeptDataSecond(params)
    }
    getsList()
}
// 头部统计
const GetViewCount = async (params) => {
    viewCountLoading.value = true
    const { data = null } = await getViewCount(params)
    viewCountData.value = data
    viewCountLoading.value = false
}
// 柱状图
const GetDeptViewCont = async (params) => {
    deptViewContLoading.value = true
    const { msg = '' } = await getDeptViewCont(params)
    const obj = JSON.parse(msg)
    deptViewContData.value = obj
    barInit()
    deptViewContLoading.value = false
}
// 饼图
const GetDataDeptProportion = async (params) => {
    pieLoading.value = true
    const { msg = '' } = await getDataDeptProportion(params)
    const data = JSON.parse(msg)
    let dataOne = []
    let dataTwo = []
    data?.deptNames?.forEach((item, index) => {
        let objOne = {
            name: item,
            value: data?.firstAuditNums[index]
        }
        let objTwo = {
            name: item,
            value: data?.secondAuditNums[index]
        }
        dataOne.push(objOne)
        dataTwo.push(objTwo)
    })
    pieDataOne.value = dataOne
    pieDataTwo.value = dataTwo
    pieName.value = data?.deptNames
    proportion()
    pieLoading.value = false
}
// 各部门审批数据汇总-初审
const GetDeptData = async (params) => {
    tableOneLoading.value = true
    const { data = [] } = await getDeptData(params)
    tableDataOne.value = data
    tableOneLoading.value = false
}
// 各部门审批数据汇总-复审
const GetDeptDataSecond = async (params) => {
    tableTwoLoading.value = true
    const { data = [] } = await getDeptDataSecond(params)
    tableDataTwo.value = data
    tableTwoLoading.value = false
}
/** 获取招商部门列表 */
const getsList = async () => {
    const { data = [] } = await getSystemList({ parentId: '1796913597400784898' })
    if (data && data.length) {
        queryParmas.value.recruiterDeptId = data[0].deptId
        data.forEach(item => {
            if (item.deptName === '惠麦优选') {
                tabsId.value = item.deptId
            }
        })
    }
    tabsData.value = data
    handleClick()
}
// tabs切换操作
const handleClick = () => {
    queryParmas.value.pageNum = 1
    let params = {
        ...queryParmas.value,
        startDate: queryParmas.value.dateOne && queryParmas.value.dateOne[0] || '',
        endDate: queryParmas.value.dateOne && queryParmas.value.dateOne[1] || '',
    }
    if (chartTabsId.value === 1) {
        GetDeptDataList()
    } else {
        GetDeptDataListSecond(params)
    }
}
// 各部门审批数据详细信息-初审
const GetDeptDataList = async () => {
    let params = {
        ...queryParmas.value,
        startDate: queryParmas.value.dateOne && queryParmas.value.dateOne[0] || '',
        endDate: queryParmas.value.dateOne && queryParmas.value.dateOne[1] || '',
    }
    tableThreeLoading.value = true
    const { rows = [], total = 0 } = await getDeptDataList(params)
    tableDataThree.value = rows
    tableThreeTotal.value = total
    tableThreeLoading.value = false
}
// 各部门审批数据详细信息-复审
const GetDeptDataListSecond = async (params) => {
    tableThreeLoading.value = true
    const { rows = [], total = 0 } = await getDeptDataListSecond(params)
    tableDataThree.value = rows
    tableThreeTotal.value = total
    tableThreeLoading.value = false
}
// 顶部检索
const onSubmitOne = debounce(() => {
    queryParmas.value.status = ''
    getListOne()
}, 500)
// 柱状图检索
const onSubmitTwo = debounce(() => {
    getListTwo()
}, 500)
// 时间type点击
const statusChange = debounce((e) => {
    if (e === '今日视图') {
        queryParmas.value.date = [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    }
    if (e === '本周视图') {
        queryParmas.value.date = [dayjs().subtract(7, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    }
    if (e === '本月视图') {
        queryParmas.value.date = [dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    }
    if (e === '本年视图') {
        queryParmas.value.date = [dayjs().subtract(365, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    }
    getListOne()
    getListTwo()
}, 200)
// 柱图tabs切换
const chartTabsClick = (id) => {
    chartTabsId.value = id
    getListTwo()
}
/** 导出按钮操作 */
const handleExport = debounce(() => {
    const params = {
        startDate: queryParmas.value.dateOne && queryParmas.value.dateOne[0] || '',
        endDate: queryParmas.value.dateOne && queryParmas.value.dateOne[1] || '',
    }
    if (chartTabsId.value === 1) {
        proxy?.downloadAsync("basic/getDeptDataExport", {
            ...params,
        }, `核价数据${dayjs(params.startDate).format('YYYYMMDD')}-${dayjs(params.endDate).format('YYYYMMDD')}.xlsx`)
    } else {
        proxy?.downloadAsync("basic/getDeptDataSecondExport", {
            ...params,
        }, `核价数据${dayjs(params.startDate).format('YYYYMMDD')}-${dayjs(params.endDate).format('YYYYMMDD')}.xlsx`)
    }
}, 500)
const routerPath = () => {
    router.push({
        path: '/pricing/productSelectionPricing'
    })
}
// 柱图
const barInit = async () => {
    let series = []
    if (chartTabsId.value === 1) {
        series = [
            // {
            //     name: '资质通过率',
            //     data: deptViewContData.value?.passFirst,
            //     type: 'bar',
            //     itemStyle: {
            //         color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            //             { offset: 0, color: '#37FF72' },
            //             { offset: 1, color: '#62E158' }
            //         ]),
            //         borderRadius: [5, 5, 0, 0]
            //     },
            //     label: {
            //         show: true,
            //         color: '#19D11B',
            //         position: 'top',
            //         formatter: (params) => {
            //             let num = (Number(params.value) || 0) / (deptViewContData.value?.requestFirst && deptViewContData.value?.requestFirst[params.dataIndex])
            //             if (!isNaN(num)) {
            //                 return `${(num * 100).toFixed(2)}%`
            //             } else {
            //                 return '0%'
            //             }
            //         }
            //     },
            // },
            {
                name: '通过率',
                data: deptViewContData.value?.rejectFirst,
                type: 'bar',
                barWidth:'40',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#40A5FF' },
                        { offset: 1, color: '#1E6CFE' }
                    ]),
                    borderRadius: [5, 5, 0, 0]
                },
                label: {
                    show: true,
                    color: '#0094FF',
                    position: 'top',
                    formatter: (params) => {
                        let num = (Number(params.value) || 0) / (deptViewContData.value?.requestFirst && deptViewContData.value?.requestFirst[params.dataIndex])
                        if (!isNaN(num)) {
                            return `${(num * 100).toFixed(2)}%`
                        } else {
                            return '0%'
                        }
                    }
                },
            }
        ]
    } else {
        series = [
            {
                name: '复核通过',
                data: deptViewContData.value?.passSecond,
                type: 'bar',
                stack: 'total',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#40A5FF' },
                        { offset: 1, color: '#1E6CFE' }
                    ]),
                },
                label: {
                    show: true,
                    color: '#fff'
                },
            },
            {
                name: '复核驳回',
                data: deptViewContData.value?.rejectSecond,
                type: 'bar',
                stack: 'total',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#FF7740' },
                        { offset: 1, color: '#FE531E' }
                    ]),
                },
                label: {
                    show: true,
                    color: '#fff'
                },
            }
        ]
    }
    await nextTick(); // 确保DOM已经渲染完成
    chartInstanceBar = echarts.init(chartBarDom.value);
    let option = {
        legend: {},
        tooltip: {},
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: deptViewContData.value?.deptNameFirst,
            axisTick: {
                alignWithLabel: true
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#1A1B1C'
                }
            },
        },
        yAxis: {
            type: 'value',
            alignTicks: true,
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#DCDFE6',
                    type: 'dashed'
                }
            },
            splitLine: {
                lineStyle: {
                    type: 'dashed'
                }
            }
        },
        series: series
    };
    chartInstanceBar.setOption(option, true);
    // 为了健壮性，可以考虑一下这里获取dom元素进行一个判断，如果没有获取到dom元素就不进行监听，这里就这样了
    erd.listenTo(chartBarDom.value, function () {
        chartInstanceBar.resize()
    });
}
// 饼图
const proportion = async () => {
    await nextTick(); // 确保DOM已经渲染完成
    chartInstancePie = echarts.init(chartPieDom.value);
    let colorList = ['#73DDFF', '#73ACFF', '#FDD56A', '#FDB36A', '#FD866A', '#9E87FF', '#58D5FF'];
    let option = {
        tooltip: {
            trigger: 'item',

            borderWidth: 1,
            padding: 5,
            formatter: function (parms) {
                let str = parms.marker + "" + parms.data.name + "</br>" +
                    "数量：" + parms.data.value + "</br>" +
                    "占比：" + parms.percent + "%";
                return str;
            }
        },
        legend: {
            type: "scroll",
            top: '5%',
            textStyle: {
                color: 'auto',
                fontSize: 14
            },
            data: pieName.value
        },
        series: [{
            type: 'pie',
            z: 3,
            center: ['50%', '60%'],
            radius: ['25%', '45%'],
            clockwise: true,
            avoidLabelOverlap: true,
            hoverOffset: 15,
            itemStyle: {
                normal: {
                    color: function (params) {
                        return colorList[params.dataIndex]
                    }
                }
            },
            label: {
                show: true,
                position: 'outside',
                formatter: '{a|{b}：{d}%}\n{hr|}',
                rich: {
                    hr: {
                        backgroundColor: 't',
                        borderRadius: 3,
                        width: 3,
                        height: 3,
                        padding: [3, 3, 0, -12]
                    },
                    a: {
                        padding: [-30, 15, -20, 15],
                        fontSize: 16
                    }
                },
                color: "auto",
            },
            labelLine: {
                normal: {
                    length: 20,
                    length2: 30,
                    lineStyle: {
                        width: 1
                    }
                }
            },
            data: chartTabsId.value === 1 ? pieDataOne.value : pieDataTwo.value
        }
        ]
    };
    chartInstancePie.setOption(option, true);
    // 为了健壮性，可以考虑一下这里获取dom元素进行一个判断，如果没有获取到dom元素就不进行监听，这里就这样了
    erd.listenTo(chartPieDom.value, function () {
        chartInstancePie.resize()
    });
}
// 初始化ECharts实例并设置配置项（这里以折线图为例，但可灵活替换）
onMounted(() => {
    queryParmas.value.date = [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    queryParmas.value.dateOne = [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
    getListOne()
    getListTwo()
});
// 销毁ECharts实例
onUnmounted(() => {
    if (chartInstancePie != null && chartInstancePie.dispose) {
        chartInstancePie.dispose();
    }
    if (chartInstanceBar != null && chartInstanceBar.dispose) {
        chartInstanceBar.dispose();
    }
    erd.uninstall(chartPieDom.value)
    erd.uninstall(chartBarDom.value)
});
</script>
<style lang="scss" scoped>
@import url(./components/style/index.scss);
</style>